package com.lcw.library.imagepicker.manager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lcw.library.imagepicker.utils.PermissionUtil;

/**
 * 更多媒体访问Fragment
 * 
 * 用于处理Android 14+的更多媒体访问权限请求
 * 当用户只授予部分选择权限时，可以通过此Fragment请求更多媒体文件访问权限
 * 
 */
public class MoreMediaAccessFragment extends Fragment {

    private static final int REQUEST_MORE_MEDIA_ACCESS = 1002;
    private MoreMediaAccessCallback callback;

    public interface MoreMediaAccessCallback {
        void onMoreMediaAccessResult(boolean success);
    }

    public static MoreMediaAccessFragment newInstance(MoreMediaAccessCallback callback) {
        MoreMediaAccessFragment fragment = new MoreMediaAccessFragment();
        fragment.callback = callback;
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 请求更多媒体访问
        PermissionUtil.requestMoreMediaAccess(this, REQUEST_MORE_MEDIA_ACCESS);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_MORE_MEDIA_ACCESS) {
            boolean success = false;
            
            if (resultCode == Activity.RESULT_OK) {
                // 检查是否获得了更多权限
                success = PermissionUtil.checkStoragePermission(requireContext());
            }
            
            if (callback != null) {
                callback.onMoreMediaAccessResult(success);
            }
        }
        
        // 移除Fragment
        if (getFragmentManager() != null) {
            getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_MORE_MEDIA_ACCESS) {
            boolean success = PermissionUtil.checkPermissionResult(permissions, grantResults) && 
                            PermissionUtil.checkStoragePermission(requireContext());
            
            if (callback != null) {
                callback.onMoreMediaAccessResult(success);
            }
        }
        
        // 移除Fragment
        if (getFragmentManager() != null) {
            getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss();
        }
    }
} 